<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

$db = Database::getInstance();

// 初始化变量
$gameId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$game = [];
$isEdit = $gameId > 0;
$errors = [];

// 预设的游戏分类
$gameCategories = [
    '注意力训练' => '注意力训练',
    '记忆力训练' => '记忆力训练',
    '逻辑思维' => '逻辑思维',
    '空间感知' => '空间感知',
    '语言能力' => '语言能力',
    '数学能力' => '数学能力',
    '创造力' => '创造力',
    '反应速度' => '反应速度',
    '其他' => '其他'
];

// 如果是编辑模式，获取游戏信息
if ($isEdit) {
    $game = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "games WHERE id = ?", [$gameId]);
    
    if (!$game) {
        $_SESSION['flash_message'] = '游戏不存在';
        $_SESSION['flash_type'] = 'danger';
        header('Location: games.php');
        exit;
    }
    
    // 确保自定义的分类也显示在下拉列表中
    if (!isset($gameCategories[$game['category']])) {
        $gameCategories[$game['category']] = $game['category'];
    }
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取表单数据
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $rules = trim($_POST['rules'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $customCategory = trim($_POST['custom_category'] ?? '');
    $difficulty = (int)($_POST['difficulty'] ?? 1);
    $status = $_POST['status'] ?? 'active';
    $minAge = (int)($_POST['min_age'] ?? 0);
    $maxAge = (int)($_POST['max_age'] ?? 0);
    $playTime = (int)($_POST['play_time'] ?? 0);
    $instructions = trim($_POST['instructions'] ?? '');
    
    // 如果选择了自定义分类，则使用自定义分类
    if ($category === 'custom' && !empty($customCategory)) {
        $category = $customCategory;
        // 添加到分类列表中，以便在表单验证错误时显示
        $gameCategories[$category] = $category;
    }
    
    // 验证表单数据
    if (empty($name)) {
        $errors['name'] = '游戏名称不能为空';
    } elseif (strlen($name) > 100) {
        $errors['name'] = '游戏名称不能超过100个字符';
    }
    
    if (empty($description)) {
        $errors['description'] = '游戏描述不能为空';
    }
    
    if (empty($category)) {
        $errors['category'] = '游戏分类不能为空';
    }
    
    if ($difficulty < 1 || $difficulty > 5) {
        $errors['difficulty'] = '难度级别必须在1到5之间';
    }
    
    if ($minAge < 0) {
        $errors['min_age'] = '最小年龄不能为负数';
    }
    
    if ($maxAge < $minAge && $maxAge > 0) {
        $errors['max_age'] = '最大年龄不能小于最小年龄';
    }
    
    if ($playTime < 0) {
        $errors['play_time'] = '游戏时长不能为负数';
    }
    
    // 检查游戏名称是否已存在
    $existingSql = "SELECT id FROM " . DB_PREFIX . "games WHERE name = ?";
    $existingParams = [$name];
    
    if ($isEdit) {
        $existingSql .= " AND id != ?";
        $existingParams[] = $gameId;
    }
    
    $existingGame = $db->fetchRow($existingSql, $existingParams);
    
    if ($existingGame) {
        $errors['name'] = '该游戏名称已被使用';
    }
    
    // 处理游戏图片上传
    $image = $isEdit ? $game['image'] : '';
    
    if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
        $result = uploadImage('image', '../uploads/games/');
        
        if ($result['success']) {
            $image = $result['path'];
            
            // 如果是编辑模式且有旧图片，删除旧图片
            if ($isEdit && !empty($game['image']) && file_exists('../' . $game['image'])) {
                @unlink('../' . $game['image']);
            }
        } else {
            $errors['image'] = $result['message'];
        }
    }
    
    // 如果没有错误，保存数据
    if (empty($errors)) {
        $gameData = [
            'name' => $name,
            'description' => $description,
            'rules' => $rules,
            'category' => $category,
            'difficulty' => $difficulty,
            'status' => $status,
            'min_age' => $minAge,
            'max_age' => $maxAge,
            'play_time' => $playTime,
            'instructions' => $instructions,
            'image' => $image
        ];
        
        if ($isEdit) {
            // 更新游戏
            $gameData['updated_at'] = date('Y-m-d H:i:s');
            $db->update('games', $gameData, 'id = ?', [$gameId]);
            
            $_SESSION['flash_message'] = '游戏信息已更新';
            $_SESSION['flash_type'] = 'success';
        } else {
            // 添加游戏
            $gameData['created_at'] = date('Y-m-d H:i:s');
            $gameData['updated_at'] = date('Y-m-d H:i:s');
            $db->insert('games', $gameData);
            
            $_SESSION['flash_message'] = '游戏添加成功';
            $_SESSION['flash_type'] = 'success';
        }
        
        header('Location: games.php');
        exit;
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><?php echo $isEdit ? '<i class="bi bi-pencil"></i> 编辑游戏' : '<i class="bi bi-plus-circle"></i> 添加游戏'; ?></h1>
    <a href="games.php" class="btn btn-secondary">
        <i class="bi bi-arrow-left"></i> 返回游戏列表
    </a>
</div>

<div class="card mb-4">
    <div class="card-header">
        <?php echo $isEdit ? '编辑游戏信息' : '填写游戏信息'; ?>
    </div>
    <div class="card-body">
        <form action="" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="name" class="form-label">游戏名称 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control <?php echo isset($errors['name']) ? 'is-invalid' : ''; ?>" 
                           id="name" name="name" 
                           value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ($isEdit ? htmlspecialchars($game['name']) : ''); ?>" 
                           required>
                    <?php if (isset($errors['name'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['name']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label class="form-label">游戏分类 <span class="text-danger">*</span></label>
                    <div class="input-group <?php echo isset($errors['category']) ? 'is-invalid' : ''; ?>">
                        <select class="form-select" id="category" name="category" onchange="toggleCustomCategory()">
                            <?php foreach ($gameCategories as $value => $label): ?>
                                <option value="<?php echo htmlspecialchars($value); ?>" 
                                        <?php 
                                        $selectedCategory = isset($_POST['category']) ? $_POST['category'] : ($isEdit ? $game['category'] : '');
                                        echo $selectedCategory === $value ? 'selected' : ''; 
                                        ?>>
                                    <?php echo htmlspecialchars($label); ?>
                                </option>
                            <?php endforeach; ?>
                            <option value="custom">自定义分类...</option>
                        </select>
                    </div>
                    <div id="custom-category-group" class="mt-2" style="display: none;">
                        <input type="text" class="form-control" id="custom_category" name="custom_category" 
                               placeholder="请输入自定义分类">
                    </div>
                    <?php if (isset($errors['category'])): ?>
                        <div class="invalid-feedback d-block"><?php echo $errors['category']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-12 mb-3">
                    <label for="description" class="form-label">游戏描述 <span class="text-danger">*</span></label>
                    <textarea class="form-control <?php echo isset($errors['description']) ? 'is-invalid' : ''; ?>" 
                              id="description" name="description" rows="3" required><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ($isEdit ? htmlspecialchars($game['description']) : ''); ?></textarea>
                    <?php if (isset($errors['description'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['description']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-12 mb-3">
                    <label for="rules" class="form-label">游戏规则</label>
                    <textarea class="form-control" id="rules" name="rules" rows="4"><?php echo isset($_POST['rules']) ? htmlspecialchars($_POST['rules']) : ($isEdit ? htmlspecialchars($game['rules']) : ''); ?></textarea>
                </div>
                
                <div class="col-md-12 mb-3">
                    <label for="instructions" class="form-label">操作指南</label>
                    <textarea class="form-control" id="instructions" name="instructions" rows="3"><?php echo isset($_POST['instructions']) ? htmlspecialchars($_POST['instructions']) : ($isEdit ? htmlspecialchars($game['instructions']) : ''); ?></textarea>
                </div>
                
                <div class="col-md-3 mb-3">
                    <label for="difficulty" class="form-label">难度级别</label>
                    <select class="form-select <?php echo isset($errors['difficulty']) ? 'is-invalid' : ''; ?>" 
                            id="difficulty" name="difficulty">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                            <option value="<?php echo $i; ?>" 
                                    <?php 
                                    $selectedDifficulty = isset($_POST['difficulty']) ? (int)$_POST['difficulty'] : ($isEdit ? (int)$game['difficulty'] : 1);
                                    echo $selectedDifficulty === $i ? 'selected' : ''; 
                                    ?>>
                                <?php 
                                $difficultyLabels = [1 => '非常简单', 2 => '简单', 3 => '中等', 4 => '困难', 5 => '非常困难'];
                                echo $difficultyLabels[$i]; 
                                ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                    <?php if (isset($errors['difficulty'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['difficulty']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-3 mb-3">
                    <label for="status" class="form-label">状态</label>
                    <select class="form-select" id="status" name="status">
                        <option value="active" <?php echo (isset($_POST['status']) ? $_POST['status'] === 'active' : ($isEdit ? $game['status'] === 'active' : true)) ? 'selected' : ''; ?>>活跃</option>
                        <option value="inactive" <?php echo (isset($_POST['status']) ? $_POST['status'] === 'inactive' : ($isEdit ? $game['status'] === 'inactive' : false)) ? 'selected' : ''; ?>>禁用</option>
                    </select>
                </div>
                
                <div class="col-md-2 mb-3">
                    <label for="min_age" class="form-label">最小年龄</label>
                    <input type="number" class="form-control <?php echo isset($errors['min_age']) ? 'is-invalid' : ''; ?>" 
                           id="min_age" name="min_age" min="0" 
                           value="<?php echo isset($_POST['min_age']) ? (int)$_POST['min_age'] : ($isEdit ? (int)$game['min_age'] : 0); ?>">
                    <?php if (isset($errors['min_age'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['min_age']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-2 mb-3">
                    <label for="max_age" class="form-label">最大年龄</label>
                    <input type="number" class="form-control <?php echo isset($errors['max_age']) ? 'is-invalid' : ''; ?>" 
                           id="max_age" name="max_age" min="0" 
                           value="<?php echo isset($_POST['max_age']) ? (int)$_POST['max_age'] : ($isEdit ? (int)$game['max_age'] : 0); ?>">
                    <small class="form-text text-muted">0表示无限制</small>
                    <?php if (isset($errors['max_age'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['max_age']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-2 mb-3">
                    <label for="play_time" class="form-label">游戏时长(秒)</label>
                    <input type="number" class="form-control <?php echo isset($errors['play_time']) ? 'is-invalid' : ''; ?>" 
                           id="play_time" name="play_time" min="0" 
                           value="<?php echo isset($_POST['play_time']) ? (int)$_POST['play_time'] : ($isEdit ? (int)$game['play_time'] : 0); ?>">
                    <small class="form-text text-muted">0表示无限制</small>
                    <?php if (isset($errors['play_time'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['play_time']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="image" class="form-label">游戏图片</label>
                    <input type="file" class="form-control <?php echo isset($errors['image']) ? 'is-invalid' : ''; ?>" 
                           id="image" name="image" accept="image/*">
                    <small class="form-text text-muted">建议尺寸: 300x300像素</small>
                    <?php if (isset($errors['image'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['image']; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($isEdit && !empty($game['image'])): ?>
                        <div class="mt-2">
                            <img src="<?php echo htmlspecialchars($game['image']); ?>" alt="当前图片" class="img-thumbnail" style="max-width: 150px;">
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> <?php echo $isEdit ? '保存修改' : '添加游戏'; ?>
                </button>
                <a href="games.php" class="btn btn-secondary ms-2">
                    <i class="bi bi-x"></i> 取消
                </a>
            </div>
        </form>
    </div>
</div>

<script>
function toggleCustomCategory() {
    const categorySelect = document.getElementById('category');
    const customCategoryGroup = document.getElementById('custom-category-group');
    
    if (categorySelect.value === 'custom') {
        customCategoryGroup.style.display = 'block';
    } else {
        customCategoryGroup.style.display = 'none';
    }
}

// 初始化页面时调用一次，以确保状态正确
document.addEventListener('DOMContentLoaded', function() {
    toggleCustomCategory();
});
</script>

<?php
require_once 'includes/footer.php';
?> 